package com.starbucks.opencase.tool;

import com.starbucks.opencase.modualr.moGoodsSummary;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class toolUserGoods {
    @Autowired
    private JdbcTemplate con;

    /**
     * 添加物品
     * @param uid
     * @param gid
     * @param num
     */
    public void addGoods(String uid,String gid,int num){
        int n=con.queryForObject("select if(isnull(gid),-1,count(*)) from user_goods_bag where uid=? and gid=?", Integer.class,uid,gid);
        if(n<0){
            con.update("insert into user_goods_bag values(?,?,?)",uid,gid,num);
        }else{
            con.update("update user_goods_bag set num=num+? where uid=? and gid=?",num,uid,gid);
        }
    }

    /**
     * 查询物品列表
     * @param uid
     * @return
     */
    public List<moGoodsSummary> queryGoods(String uid){
        return con.query("select a.gid,a.num,b.name from user_goods_bag as a join goods_info as b on a.gid=b.gid where uid=?",new BeanPropertyRowMapper<>(moGoodsSummary.class),uid);
    }

    /**
     * 查询物品
     * @param uid
     * @param gid
     * @return
     */
    public moGoodsSummary queryGoods(String uid,String gid){
        List<moGoodsSummary> as=con.query("select a.gid,a.num,b.name from user_goods_bag as a join goods_info as b on a.gid=b.gid where uid=? and a.gid=?",new BeanPropertyRowMapper<>(moGoodsSummary.class),uid,gid);
        if(as.isEmpty())return new moGoodsSummary();
        return as.get(0);
    }
    public String queryName(String gid){
        try {
            return con.queryForObject("select name from goods_info where gid=?", String.class, gid);
        }catch (Exception e){
            return "";
        }
    }
    public long queryUseTime(String gid){
        try{
            return con.queryForObject("select useTime from goods_info where gid=?", Long.class,gid);
        }catch (Exception e){
            return 0;
        }
    }
}
